package com.shenmazong.serveredustudent.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shenmazong.serveredustudent.mapper.*;
import com.shenmazong.serveredustudent.pojo.*;
import com.shenmazong.serveredustudent.service.TbStudentService;
import com.shenmazong.serveredustudent.vo.StudentVo;
import com.shenmazong.utils.ResultResponse;
import com.shenmazong.vo.ListParamVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 *
 */
@Service
@Transactional
public class TbStudentServiceImpl extends ServiceImpl<TbStudentMapper, TbStudent>
        implements TbStudentService {

    @Autowired
    private TbStudentMapper studentMapper;

    @Autowired
    private TbResultRecordMapper resultRecordMapper;

    @Autowired
    private TbCollageMapper collageMapper;

    @Autowired
    private TbMajorMapper majorMapper;

    @Autowired
    private TbClazzStudentMapper clazzStudentMapper;

    @Autowired
    private TbExamGradeMapper examGradeMapper;

    @Autowired
    private TbStageMapper stageMapper;

    @Autowired
    private TbClazzMapper clazzMapper;


    @Override
    public ResultResponse getStudentPage(ListParamVo listParamVo) {

        Page<StudentVo> tbStudentPage = new Page<>(listParamVo.getCurrent(), listParamVo.getSize());

        //判断参数是否正确
        if (listParamVo.getParamMap().size() == 0) {
            return ResultResponse.FAILED(-1, "參數異常");
        }
        //根据学院Id 专业ID 阶段Id 班级Id 学生Id查询信息
        IPage<TbStudent> tbStudentIPage = studentMapper.getStudentPage(tbStudentPage, listParamVo.getParamMap());

        return ResultResponse.SUCCESS(tbStudentIPage);

    }

    @Override
    public ResultResponse saveStudentToSchool(Long stuId, long collageId, long majorId, long clazzId) {

        LambdaQueryWrapper<TbStudent> last = new QueryWrapper<TbStudent>().lambda().eq(TbStudent::getStuId, stuId).last("limit 1");
        TbStudent student = studentMapper.selectOne(last);

        //判断student
        if (clazzId == 0 || collageId == 0 || majorId == 0) {
            return ResultResponse.FAILED(-1, "参数异常，学生入学失败");
        }
        //获取最后一个学生的学号
        TbStudent stu = studentMapper.getLastStudent(clazzId);

        if (stu == null) {
            //获取相应的学院
            TbCollage tbCollage = collageMapper.selectById(collageId);
            //获取相应的专业
            TbMajor tbMajor = majorMapper.selectById(majorId);
            //当前日期
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String format = simpleDateFormat.format(new Date());
            //生成学生id  格式为  学院NO+专业No+日期+排序
            String no = "" + tbCollage.getCollageNo() + tbMajor.getMajorNo() + format + 0001;
            student.setStuNo(Long.parseLong(no));
            //学生入学
            studentMapper.updateById(student);

        } else {
            Long stuNo = stu.getStuNo() + 1;
            stu.setStuNo(stuNo);
            studentMapper.updateById(student);
        }

        TbClazzStudent tbClazzStudent = new TbClazzStudent();
        tbClazzStudent.setClazzId(clazzId);
        tbClazzStudent.setStuId(student.getStuId());
        //学会班级中间表插入数据
        clazzStudentMapper.insert(tbClazzStudent);

        return ResultResponse.SUCCESS(student);

    }

    @Override
    public ResultResponse StudentTransfor(Long stuId, Long oldClazzId, Long newClazzId) {

        LambdaQueryWrapper<TbClazzStudent> last = new QueryWrapper<TbClazzStudent>().lambda().eq(TbClazzStudent::getStuId, stuId).eq(TbClazzStudent::getClazzId, oldClazzId).last("limit 1");

        //查询学生Id和班级Id对应的中间表数据
        TbClazzStudent tbClazzStudent = clazzStudentMapper.selectOne(last);

        if (tbClazzStudent != null) {
            return ResultResponse.FAILED(-1, "参数异常");
        }

        tbClazzStudent.setClazzId(newClazzId);

        clazzStudentMapper.updateById(tbClazzStudent);


        return ResultResponse.SUCCESS("转学成功");
    }


    @Override
    public ResultResponse updateStudentInfo(TbStudent student) {

        studentMapper.updateById(student);

        return ResultResponse.SUCCESS("修改成功");

    }


    @Override
    public ResultResponse deleteStudentInfo(Long stuId) {

        if (stuId == null) {
            return ResultResponse.FAILED(-1, "参数异常");
        }

        LambdaQueryWrapper<TbStudent> last = new QueryWrapper<TbStudent>().lambda().eq(TbStudent::getStuId, stuId).last("limit 1");

        studentMapper.delete(last);

        return ResultResponse.SUCCESS("删除成功");

    }

    @Override
    public ResultResponse updateStudentStatus(long stuId, Integer status) {

        if (status == null || stuId == 0) {
            return ResultResponse.FAILED(-1, "参数异常");
        }

        LambdaQueryWrapper<TbStudent> last = new QueryWrapper<TbStudent>().lambda().eq(TbStudent::getStuId, stuId).last("limit 1");

        TbStudent tbStudent = studentMapper.selectOne(last);
        //正常    1:在校，2：休学，3：毕业，4：请假，0：退学

        LambdaQueryWrapper<TbClazzStudent> eq = new QueryWrapper<TbClazzStudent>().lambda().eq(TbClazzStudent::getStuId, stuId);
        List<TbClazzStudent> tbClazzStudents = clazzStudentMapper.selectList(eq);
        for (TbClazzStudent tbClazzStudent : tbClazzStudents) {

            if (status == 0 || status == 4) {
                clazzStudentMapper.deleteById(tbClazzStudent);
            } else if (status == 1) {
                tbClazzStudent.setDeleteFlag(Byte.parseByte("0"));
                clazzStudentMapper.updateById(tbClazzStudent);
            }
        }

        tbStudent.setStuStatus(Byte.parseByte(status.toString()));

        studentMapper.updateById(tbStudent);

        return ResultResponse.SUCCESS("状态修改成功！");
    }

    @Override
    public ResultResponse changeClazzByGrade(Long stuId, Long clazzId) {
        //学生升班末班
        if (stuId == null || clazzId == null) {
            return ResultResponse.FAILED(-1, "参数异常");
        }

        LambdaQueryWrapper<TbExamGrade> last = new QueryWrapper<TbExamGrade>().lambda().eq(TbExamGrade::getStudentId, stuId).eq(TbExamGrade::getClazzId, clazzId).last("limit 1");
        //查询成绩
        TbExamGrade tbExamGrade = examGradeMapper.selectOne(last);
        //查询为空返回错误
        if (tbExamGrade == null) {
            return ResultResponse.FAILED(-1, "无考试成绩");
        }

        Byte isCheat = tbExamGrade.getIsCheat();
        BigDecimal theoryGrade = tbExamGrade.getTheoryGrade();
        BigDecimal skillGrade = tbExamGrade.getSkillGrade();

        TbResultRecord tbResultRecord = new TbResultRecord();
        tbResultRecord.setStuId(stuId);

        //理论成绩或者技能成绩不合格，末班 判断是否作弊
        if (theoryGrade.compareTo(new BigDecimal(70)) == -1 || skillGrade.compareTo(new BigDecimal(70)) == -1 || isCheat == 1) {

            tbResultRecord.setExamResult(Byte.valueOf("2"));

            resultRecordMapper.insert(tbResultRecord);
            return ResultResponse.SUCCESS("学生末班");

        } else {

            LambdaQueryWrapper<TbClazz> clazzQuery = new QueryWrapper<TbClazz>().lambda().eq(TbClazz::getClazzId, clazzId).last("limit 1");
            TbClazz tbClazz = clazzMapper.selectOne(clazzQuery);

            Long stageId = tbClazz.getStageId();

            LambdaQueryWrapper<TbStage> stageQuery = new QueryWrapper<TbStage>().lambda().eq(TbStage::getStageId, stageId).last("limit 1");

            TbStage tbStage = (TbStage) stageMapper.selectOne(stageQuery);

            Long majorId = tbStage.getMajorId();

            Byte maxStageNo = stageMapper.getMaxStageNoByMajorId(majorId);

            Byte stageNo = tbStage.getStageNo();
            //判断学生阶段编号+1大于最大的学院编号（毕业）
            if (stageNo + 1 > maxStageNo) {

                LambdaQueryWrapper<TbStudent> studentQuery = new QueryWrapper<TbStudent>().lambda().eq(TbStudent::getStuId, stuId).last("limit 1");

                TbStudent tbStudent = studentMapper.selectOne(studentQuery);

                tbStudent.setStuStatus(Byte.valueOf("3"));

                //修改学生状态（毕业状态）
                studentMapper.updateById(tbStudent);

                //删除学生信息（软删除）
                studentMapper.delete(studentQuery);

                LambdaQueryWrapper<TbClazzStudent> clazzStudentQuery = new QueryWrapper<TbClazzStudent>().lambda().eq(TbClazzStudent::getStuId, stuId).last("limit 1");
                //删除班级学生中间表 关联
                clazzStudentMapper.delete(clazzStudentQuery);

                return ResultResponse.SUCCESS("学生毕业");

            } else {

                LambdaQueryWrapper<TbClazzStudent> clazzStudentLambdaQueryWrapper = new QueryWrapper<TbClazzStudent>()
                        .lambda()
                        .eq(TbClazzStudent::getStuId, stuId)
                        .eq(TbClazzStudent::getClazzId, clazzId)
                        .last("limit 1");
                TbClazzStudent tbClazzStudent = clazzStudentMapper.selectOne(clazzStudentLambdaQueryWrapper);

                LambdaQueryWrapper<TbStage> stageLambdaQueryWrapper = new QueryWrapper<TbStage>()
                        .lambda().eq(TbStage::getMajorId, majorId)
                        .eq(TbStage::getStageNo, stageNo + 1).last("limit 1");
                TbStage stage = stageMapper.selectOne(stageLambdaQueryWrapper);

                LambdaQueryWrapper<TbClazz> clazzLambdaQueryWrapper = new QueryWrapper<TbClazz>().lambda()
                        .eq(TbClazz::getStageId, stage.getStageId())
                        .eq(TbClazz::getClazzType, tbClazz.getClazzType()).last("limit 1");

                TbClazz clazz = clazzMapper.selectOne(clazzLambdaQueryWrapper);

                tbClazzStudent.setClazzId(clazz.getClazzId());
                //学生升班更换班级
                clazzStudentMapper.updateById(tbClazzStudent);

                return ResultResponse.SUCCESS("学生升班");

            }


        }

    }

    @Override
    public ResultResponse getStudentListByCollageId(ListParamVo listParamVo) {

        Page<TbStudent> studentPage = new Page<>(listParamVo.getCurrent(), listParamVo.getSize());

        LambdaQueryWrapper<TbStudent> collageId = new QueryWrapper<TbStudent>().lambda().eq(TbStudent::getCollageId, listParamVo.getParamMap().get("collageId"));

        Page<TbStudent> studentPage1 = studentMapper.selectPage(studentPage, collageId);

        return ResultResponse.SUCCESS(studentPage1);
    }


}




